import com.ysy.tz.core.engine.ApplicationContext;
import com.ysy.tz.core.engine.DefaultKeyValuePair;
import com.ysy.tz.core.engine.Modelable;
import com.ysy.tz.core.engine.ParameterInitializable;
import com.ysy.tz.core.print.PrintWorker;
import com.ysy.tz.core.selfcomp.*;
import com.ysy.tz.core.utils.SQLUtils;
import com.ysy.tz.core.utils.SessionUtils;
import com.ysy.tz.mfg.dao.CarcassInWarehouseDao;
import com.ysy.tz.mfg.dao.CarcassOutWarehouseDao;
import com.ysy.tz.mfg.dao.CustomerDao;
import com.ysy.tz.mfg.dao.SysMachineParamDao;
import com.ysy.tz.mfg.entity.*;
import com.ysy.tz.mfg.equipment.scale.ToledoScale;
import com.ysy.tz.mfg.equipment.scale.WeightListener;
import javafx.application.Platform;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.scene.Node;
import javafx.scene.control.Alert.AlertType;
import javafx.scene.control.*;
import javafx.scene.input.KeyCode;
import javafx.scene.input.KeyEvent;
import javafx.scene.input.MouseEvent;
import javafx.scene.layout.VBox;
import javafx.scene.text.Text;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;

import java.math.BigDecimal;
import java.net.URL;
import java.text.DecimalFormat;
import java.util.*;

//毛菜称重
public class CarcassOutWarehouseController implements ParameterInitializable {
    @FXML
    DatePicker outWarehouseDate;
    @FXML
    PopupTextField customerTextField;
    @FXML
    TextField barcodeTextField;
    @FXML
    Label invQtyTextField;
    @FXML
    TableView carcassOutWarehouseTableView;
    @FXML
    TableView totalTable;
    @FXML
    TableView totalSumTable;
    @FXML
    Label outWarehouse;
    @FXML
    Label gradingLevel;
    @FXML
    Label gradingSlaughterType;
    @FXML
    Label gradingGender;
    @FXML
    Label gradingBarcode;
    @FXML
    Label gradingBillNo;
    @FXML
    VBox barCodeBox;
    @FXML
    Label weightLabel;
    @FXML
    NodeTableColumn tableOpeBtn;
    @FXML
    KeyValueTableColumn tb_slaughterType;
    @FXML
    KeyValueTableColumn tb_gender;
    @FXML
    KeyValueTableColumn tb_mjType;
    @FXML
    CheckBox printCheckBox;
    CarcassInWarehouseEntity carcassInWarehouseEntity;
    ToledoScale toledoScale = new ToledoScale();
    DecimalFormat decimalFormat = new DecimalFormat("#.##");
    private HashMap<String, String> dictMap = new HashMap();
    private volatile boolean stopRandomWeight = true;
    private Random random = new Random();
    PrintWorker printWorker;

    public CarcassOutWarehouseController() {
    }

    public void initialize(URL location, ResourceBundle resources, Object... params) {
        this.dictMap.put("B", "剥皮");
        this.dictMap.put("T", "腿毛");
        this.dictMap.put("G", "公");
        this.dictMap.put("M", "母");
        ArrayList<DefaultKeyValuePair> slaughterTypes = new ArrayList();
        slaughterTypes.add(new DefaultKeyValuePair("B", "扒皮"));
        slaughterTypes.add(new DefaultKeyValuePair("T", "褪毛"));
        this.tb_slaughterType.setKeyValuePairs(slaughterTypes);
        ArrayList<DefaultKeyValuePair> genders = new ArrayList();
        genders.add(new DefaultKeyValuePair("G", "公"));
        genders.add(new DefaultKeyValuePair("M", "母"));
        this.tb_gender.setKeyValuePairs(genders);
        ArrayList<DefaultKeyValuePair> mjTypes = new ArrayList();
        mjTypes.add(new DefaultKeyValuePair("M", "毛腔"));
        mjTypes.add(new DefaultKeyValuePair("J", "净腔"));
        this.tb_mjType.setKeyValuePairs(mjTypes);

        this.initScale();
        ApplicationContext.executor.execute(() -> {
            while(!this.stopRandomWeight) {
                try {
                    Platform.runLater(() -> {
                        this.weightLabel.textProperty().set(this.decimalFormat.format(20.0 + this.random.nextDouble() * 20.0));
                    });
                    Thread.sleep(1000L);
                } catch (InterruptedException var2) {
                    var2.printStackTrace();
                }
            }

        });
        this.customerTextField.addTextChangeListener(new TextChangeListener<CustomerEntity>() {
            public ObservableList textChanged(TextInputControl textField, String newValue) {
                return (ObservableList)SQLUtils.executeSQLWithReturn(CustomerDao.class, (customerDao) -> {
                    try {
                        CustomerEntity customerEntity = new CustomerEntity();
                        int enterpriseId = ((UserEntity)SessionUtils.getAttribute(SessionUtils.CURRENT_USER)).getEnterpriseId();
                        customerEntity.setEnterpriseId(enterpriseId);
                        customerEntity.setKeyWord(newValue);
                        ArrayList<CustomerEntity> customerEntities = customerDao.listForPage(customerEntity);
                        return FXCollections.observableList(customerEntities);
                    } catch (Exception var5) {
                        var5.printStackTrace();
                        return null;
                    }
                });
            }

            public void PopupChoise(CustomerEntity customerEntity) {
                CarcassOutWarehouseController.this.customerTextField.setModel(customerEntity);
                CarcassOutWarehouseController.this.barcodeTextField.requestFocus();
                CarcassOutWarehouseController.this.showCurrentOutWarehouseInfo();
            }
        });
        this.tableOpeBtn.setAction((bizEvent) -> {
            if (bizEvent.getAction().equals("delete")) {
                CarcassOutWarehouseEntity carcassOutWarehouseEntity = (CarcassOutWarehouseEntity)bizEvent.getData();
                Optional<ButtonType> result = (new CustomerAlert(AlertType.CONFIRMATION, "<TextFlow><Text>确定删除 客户[ </Text><Text style=\"-fx-font-size:14;-fx-stroke: blue;-fx-font-weight: normal;\">" + carcassOutWarehouseEntity.getCustomerName() + "</Text><Text> ], 品名[ </Text><Text style=\"-fx-font-size:14;-fx-stroke: #454926;-fx-font-weight: normal;\">" + carcassOutWarehouseEntity.getItemName() + "</Text><Text> ], 等级[ </Text><Text style=\"-fx-font-size:16;-fx-stroke: #f15b6c;-fx-font-weight: normal;\">" + carcassOutWarehouseEntity.getLevelCode() + "</Text><Text> ], 条码:[ </Text><Text style=\"-fx-font-size:14;-fx-stroke: #f15b6c;-fx-font-weight: normal;\">" + carcassOutWarehouseEntity.getBarcode() + "</Text><Text> ] ?</Text></TextFlow>", new ButtonType[0])).showAndWait();
                if (result.get() == ButtonType.OK) {
                    try {
                        SQLUtils.executeSQLTransException((sqlSession) -> {
                            CarcassOutWarehouseDao carcassOutWarehouseDao = (CarcassOutWarehouseDao)sqlSession.getMapper(CarcassOutWarehouseDao.class);
                            carcassOutWarehouseDao.delete(carcassOutWarehouseEntity.getSeqId(), carcassOutWarehouseEntity.getEnterpriseId());
                            CarcassInWarehouseDao carcassInWarehouseDao = (CarcassInWarehouseDao)sqlSession.getMapper(CarcassInWarehouseDao.class);
                            carcassInWarehouseDao.changeInWarehouseRecordStatus(carcassOutWarehouseEntity.getBarcode(), "N", carcassOutWarehouseEntity.getEnterpriseId());
                        });
                        this.showCurrentOutWarehouseInfo();
                    } catch (Exception var5) {
                        var5.printStackTrace();
                    }
                }

                this.barcodeTextField.requestFocus();
            }

        });
        Platform.runLater(() -> {
            this.customerTextField.requestFocus();
        });
        this.showCurrentOutWarehouseInfo();
        this.printWorker = new PrintWorker() {
            public void setNodeValue(Node node, HashMap<String, String> values) {
                Text todayText;
                if (node.getId().equals("weight")) {
                    todayText = (Text)node;
                    todayText.setText((String)values.get("weight"));
                } else if (node.getId().equals("today")) {
                    todayText = (Text)node;
                    todayText.setText(CarcassOutWarehouseController.this.outWarehouseDate.getEditor().getText());
                }

            }
        };

        try {
            //this.printWorker.loadTemplate("file:./template/outwarehousetickers.xml", new String[]{"javafx.scene.layout.AnchorPane", "javafx.scene.layout.VBox", "javafx.scene.text.TextFlow", "javafx.scene.text.Text"});
        } catch (Exception var8) {
            var8.printStackTrace();
        }

        this.printWorker.startPrint();
    }
    private void initScale() {
        try {
            //有称数据
            //波特率
            this.toledoScale.setBaudrate(9600);
            this.toledoScale.setPortName("COM10");
            this.toledoScale.setFractionDigits(2);
            this.toledoScale.setDataBits(8);
            this.toledoScale.setStopBits(1);
            this.toledoScale.setParity(0);
            this.toledoScale.setSameCount(3);
            //比这个重量大才会称上显示0000000000000000000000
            this.toledoScale.setMinWeight(new BigDecimal(0));
            //开始解码的位数
            this.toledoScale.setStartPoint(5);
            //结束解码的位数
            this.toledoScale.setEndPoint(10);

            this.toledoScale.addWeightListener(new WeightListener() {
                public void obtainWeight(String weightStr) {
                    if (StringUtils.isNotBlank(weightStr) && Float.parseFloat(weightStr) != 0.0F) {
                        Platform.runLater(() -> {
                            CarcassOutWarehouseController.this.weightLabel.setText(weightStr);
                        });
                    }

                }
            });
            this.toledoScale.connect();
        } catch (Exception var2) {
            var2.printStackTrace();
        }

    }

    public void unload() {
        this.stopRandomWeight = true;
    }

    String barCode;
    public void enterBarCode(KeyEvent keyEvent) {
        if (keyEvent.getCode() == KeyCode.ENTER) {
            barCode = this.barcodeTextField.getText();
            this.barcodeTextField.setText("");
            if (StringUtils.isNotBlank(barCode)) {
                int index = barCode.indexOf("?");
                if (index > 0) {
                    barCode = barCode.substring(index + 1);
                }

                SQLUtils.executeSQL(CarcassInWarehouseDao.class, (carcassInWarehouseDao) -> {
                    try {
                        int enterpriseId = ((UserEntity)SessionUtils.getAttribute(SessionUtils.CURRENT_USER)).getEnterpriseId();
                        this.carcassInWarehouseEntity = carcassInWarehouseDao.exitsCarcassInWarehouseRecord(barCode, enterpriseId);
                    } catch (Exception var4) {
                        var4.printStackTrace();
                    }

                });
            } else {
                this.carcassInWarehouseEntity = null;
            }

            this.setCarcassInWarehouseView(this.carcassInWarehouseEntity);
            this.lockOutWarehouse((MouseEvent)null);
        }

    }

    private void setCarcassInWarehouseView(CarcassInWarehouseEntity carcassInWarehouseEntity) {
        if (carcassInWarehouseEntity != null) {
            this.outWarehouse.setText(carcassInWarehouseEntity.getWarehouseName());
            this.gradingLevel.setText(carcassInWarehouseEntity.getLevelCode());
            this.gradingSlaughterType.setText((String)this.dictMap.get("" + carcassInWarehouseEntity.getSlaughterType()));
            this.gradingGender.setText((String)this.dictMap.get("" + carcassInWarehouseEntity.getGender()));
            this.gradingBarcode.setText(carcassInWarehouseEntity.getBarcode());
            this.gradingBillNo.setText(carcassInWarehouseEntity.getBillNo());
            this.barCodeBox.setVisible(true);
        } else {
            this.barCodeBox.setVisible(false);
        }

    }

    public void submitOutWarehouse(MouseEvent mouseEvent) {
        Optional<ButtonType> result = (new CustomerAlert(AlertType.CONFIRMATION, "当前客户批次出库完毕?", new ButtonType[0])).showAndWait();
        if (result.get() == ButtonType.OK) {
            try {
                UserEntity currentUser = (UserEntity)SessionUtils.getAttribute(SessionUtils.CURRENT_USER);
                String workDay = "" + SessionUtils.getAttribute(SessionUtils.WORK_DAY);
                SQLUtils.executeSQLException(CarcassOutWarehouseDao.class, (carcassOutWarehouseDao) -> {
                    carcassOutWarehouseDao.finishBatchCarcaseOutWarehouseRecordOneDay(currentUser.getUserCode(), currentUser.getEnterpriseId(), workDay, ((CustomerEntity)this.customerTextField.getModel()).getCustomerId());
                });
            } catch (Exception var5) {
                var5.printStackTrace();
            }

            this.showCurrentOutWarehouseInfo();
        }

    }

    public void lockOutWarehouse(MouseEvent mouseEvent) {
        if (StringUtils.isBlank(this.outWarehouseDate.getEditor().getText())) {
            (new CustomerAlert(AlertType.WARNING, "请选择出库日期!", new ButtonType[0])).showAndWait();
            this.outWarehouseDate.requestFocus();
        } else if (this.customerTextField.getModel() == null) {
            (new CustomerAlert(AlertType.WARNING, "请选择客户!", new ButtonType[0])).showAndWait();
            this.customerTextField.requestFocus();
        } else if (this.carcassInWarehouseEntity == null) {
            (new CustomerAlert(AlertType.WARNING, "请输入条码!", new ButtonType[0])).showAndWait();
            this.barcodeTextField.requestFocus();
        } else if (this.carcassInWarehouseEntity.getIsOut().equals("Y")) {
            (new CustomerAlert(AlertType.WARNING, "当前条码: " + this.gradingBarcode.getText() + " 已经出库!", new ButtonType[0])).showAndWait();
            this.carcassInWarehouseEntity = null;
            this.barCodeBox.setVisible(false);
        } else {
            UserEntity currentUser = (UserEntity)SessionUtils.getAttribute(SessionUtils.CURRENT_USER);
            String workDay = "" + SessionUtils.getAttribute(SessionUtils.WORK_DAY);
            CarcassOutWarehouseEntity carcassOutWarehouseEntity = new CarcassOutWarehouseEntity();
            carcassOutWarehouseEntity.setEnterpriseId(currentUser.getEnterpriseId());
            carcassOutWarehouseEntity.setWorkDay(workDay);
            carcassOutWarehouseEntity.setWorkFlightsCode(currentUser.getFlightsCode());
            carcassOutWarehouseEntity.setWarehouseId(this.carcassInWarehouseEntity.getWarehouseId());
            carcassOutWarehouseEntity.setItemId(this.carcassInWarehouseEntity.getItemId());
            carcassOutWarehouseEntity.setSupplierId(this.carcassInWarehouseEntity.getSupplierId());
            carcassOutWarehouseEntity.setCustomerId(((CustomerEntity)this.customerTextField.getModel()).getCustomerId());
            carcassOutWarehouseEntity.setBarcode(this.carcassInWarehouseEntity.getBarcode());
            carcassOutWarehouseEntity.setBillNo(this.carcassInWarehouseEntity.getBillNo());
            carcassOutWarehouseEntity.setLevelCode(this.carcassInWarehouseEntity.getLevelCode());
            carcassOutWarehouseEntity.setSlaughterType(this.carcassInWarehouseEntity.getSlaughterType());
            carcassOutWarehouseEntity.setGender(this.carcassInWarehouseEntity.getGender());
            carcassOutWarehouseEntity.setInvqty(Integer.parseInt(this.invQtyTextField.getText()));
            carcassOutWarehouseEntity.setWeight(new BigDecimal(this.weightLabel.getText()));
            carcassOutWarehouseEntity.setMjType(this.carcassInWarehouseEntity.getMjType());
            carcassOutWarehouseEntity.setCreateUserCode(currentUser.getUserCode());
            carcassOutWarehouseEntity.setCreateUserName(currentUser.getUserName());
            carcassOutWarehouseEntity.setOutWarehouseDay(this.outWarehouseDate.getEditor().getText());
            boolean success = false;

            try {
                SQLUtils.executeSQLTransException((sqlSession) -> {
                    CarcassOutWarehouseDao carcassOutWarehouseDao = (CarcassOutWarehouseDao)sqlSession.getMapper(CarcassOutWarehouseDao.class);
                    carcassOutWarehouseDao.save(carcassOutWarehouseEntity);
                    CarcassInWarehouseDao carcassInWarehouseDao = (CarcassInWarehouseDao)sqlSession.getMapper(CarcassInWarehouseDao.class);
                    carcassInWarehouseDao.changeInWarehouseRecordStatus(this.carcassInWarehouseEntity.getBarcode(), "Y", this.carcassInWarehouseEntity.getEnterpriseId());
                });
                success = true;
            } catch (Exception var7) {
                var7.printStackTrace();
                (new CustomerAlert(AlertType.WARNING, "插入数据库异常，请联系管理员!", new ButtonType[0])).showAndWait();
            }

            if (success) {
                this.showCurrentOutWarehouseInfo();
                this.barcodeTextField.requestFocus();
            }

            if (this.printCheckBox.selectedProperty().get()) {
                HashMap<String, String> valueMaps = new HashMap();
                valueMaps.put("weight", this.weightLabel.getText() + "KG");
                this.printWorker.addPrintObject(valueMaps);
            }

        }
    }

    private void showCurrentOutWarehouseInfo() {
        UserEntity currentUser = (UserEntity)SessionUtils.getAttribute(SessionUtils.CURRENT_USER);
        String workDay = "" + SessionUtils.getAttribute(SessionUtils.WORK_DAY);
        if (this.customerTextField.getModel() != null) {
            try {
                ArrayList<CarcassOutWarehouseEntity> carcassOutWarehouseEntities = (ArrayList)SQLUtils.executeSQLWithReturnException(CarcassOutWarehouseDao.class, (carcassOutWarehouseDao) -> {
                    return carcassOutWarehouseDao.searchBatchCarcaseOutWarehouseRecordOneDay(currentUser.getUserCode(), currentUser.getEnterpriseId(), workDay, ((CustomerEntity)this.customerTextField.getModel()).getCustomerId());
                });
                this.carcassOutWarehouseTableView.setItems(FXCollections.observableList(carcassOutWarehouseEntities));
                if (CollectionUtils.isNotEmpty(carcassOutWarehouseEntities)) {
                    this.showStatisticsInfo();
                } else {
                    this.totalTable.setItems(FXCollections.emptyObservableList());
                    this.totalSumTable.setItems(FXCollections.emptyObservableList());
                }
            } catch (Exception var4) {
                var4.printStackTrace();
            }

        }
    }

    private void showStatisticsInfo() {
        UserEntity currentUser = (UserEntity)SessionUtils.getAttribute(SessionUtils.CURRENT_USER);
        String workDay = "" + SessionUtils.getAttribute(SessionUtils.WORK_DAY);

        try {
            ArrayList<CarcassOutWarehouseEntity> carcassOutWarehouseEntities = (ArrayList)SQLUtils.executeSQLWithReturnException(CarcassOutWarehouseDao.class, (carcassOutWarehouseDao) -> {
                return carcassOutWarehouseDao.searchStatisticsCustomerRecordOneDay(currentUser.getUserCode(), currentUser.getEnterpriseId(), workDay, ((CustomerEntity)this.customerTextField.getModel()).getCustomerId());
            });
            this.totalTable.setItems(FXCollections.observableList(carcassOutWarehouseEntities));
            CarcassOutWarehouseEntity carcassOutWarehouseEntity = new CarcassOutWarehouseEntity();
            carcassOutWarehouseEntity.setWeight(new BigDecimal(0));
            carcassOutWarehouseEntity.setInvqty(0);
            carcassOutWarehouseEntity.setLevelCode("合计:");
            if (CollectionUtils.isNotEmpty(carcassOutWarehouseEntities)) {
                Iterator var5 = carcassOutWarehouseEntities.iterator();

                while(var5.hasNext()) {
                    CarcassOutWarehouseEntity outWarehouseEntity = (CarcassOutWarehouseEntity)var5.next();
                    carcassOutWarehouseEntity.setWeight(carcassOutWarehouseEntity.getWeight().add(outWarehouseEntity.getWeight()));
                    carcassOutWarehouseEntity.setInvqty(carcassOutWarehouseEntity.getInvqty() + outWarehouseEntity.getInvqty());
                }
            }

            this.totalSumTable.setItems(FXCollections.observableList(Arrays.asList(carcassOutWarehouseEntity)));
            this.totalTable.refresh();
            this.totalSumTable.refresh();
        } catch (Exception var7) {
            var7.printStackTrace();
        }

    }

    public void clearChoise(MouseEvent mouseEvent) {
        this.customerTextField.setModel((Modelable)null);
        this.carcassInWarehouseEntity = null;
        this.setCarcassInWarehouseView(this.carcassInWarehouseEntity);
    }

    public void showOutWarehouseDialog(MouseEvent mouseEvent) {
        Dialog dialog = CommonDialog.loadFXMLDialog("羊胴体出库明细查询", "CarcassOutWarehouseList", "CarcassOutWarehouse", new Object[0]);
        dialog.showAndWait();
    }
}
